#pragma once  
#include<iostream>
#include<string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdarg.h>

#define Screen 1
#define Onefile 2
#define Classfile 3

#define SIZE 1024

#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4

#define LogFile "log.txt"
class Log
{
public:

    Log()
    {
        printMethod=Screen;
        path = "./log/";
    }
    ~Log()
    {

    }
    void printOneFile(const std::string &logname,const std::string &logtxt)
    {
        std::string logname_=path+logname;
        int fd=open(logname_.c_str(),O_WRONLY|O_CREAT|O_APPEND,0666);
        if(fd<0)
        {
            return;
        }
        write(fd,logtxt.c_str(),logtxt.size());
        close(fd);
        
    }
    std::string levelToString(const int level)
    {
         switch (level)
        {
        case Info:
            return "Info";
        case Debug:
            return "Debug";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
        case Fatal:
            return "Fatal";
        default:
            return "None";
        }
    }

    void printClassFile(const int level,const std::string &logtxt)
    {
        std::string filename=LogFile;
        filename += ".";
        filename += levelToString(level);
        printOneFile(filename, logtxt);
    }

    void printLog(const int level,const std::string &logtxt)
    {
        switch(printMethod)
        {
        case Screen:
            std::cout << logtxt << std::endl;
            break;
        case Onefile:
            printOneFile(LogFile, logtxt);
            break;
        case Classfile:
            printClassFile(level, logtxt);
            break;
        default:
            break;
        }
    }
    void operator()(int level, const char *format, ...)
    {
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t);
        char leftbuffer[SIZE];
        snprintf(leftbuffer,sizeof(leftbuffer),"[%s][%d-%d-%d %d:%d:%d]",levelToString(level).c_str()
                ,ctime->tm_year+1900,ctime->tm_mon+1,ctime->tm_mday,ctime->tm_hour,ctime->tm_min,ctime->tm_sec);
        
        va_list s;
        va_start(s, format);//将 s 初始化为指向 format 参数之后的第一个可变参数。
        char rightbuffer[SIZE];
        vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
        //vsnprintf 是一个与 snprintf 类似的函数，但它接受一个 va_list 类型的参数，而不是直接接受可变参数列表。
        //这个函数会根据 format 字符串和 s 指向的可变参数列表来格式化一个字符串，并将结果存储在 rightbuffer 中。
        va_end(s);
        //va_end 宏用于清理 va_list 变量，释放任何与之关联的资源。在调用 va_end 之后，s 不应再被使用

        char logtxt[SIZE*2];
        snprintf(logtxt,sizeof(logtxt),"%s %s",leftbuffer,rightbuffer);
         printLog(level, logtxt);
    }
private:
    int printMethod;
    std::string path;
};
